package com.thomsonreuters.elektronunified;

import com.reuters.rfa.common.Client;
import com.reuters.rfa.common.Event;
import com.reuters.rfa.omm.OMMMsg;
import com.reuters.rfa.omm.OMMState;
import com.reuters.rfa.rdm.RDMMsgTypes;
import com.reuters.rfa.session.omm.OMMItemEvent;


public class LoginClient implements Client 
{
    private RDMCallbacks mainApp;
    public static enum LoginState { PENDING, LOGGED_IN, DENIED };
    private LoginState currentState = LoginState.PENDING;

    public LoginState getLoginState() 
    {
        return currentState;
    }

    public LoginClient(RDMCallbacks mainApp) 
    {
        this.mainApp = mainApp;
    }

    @Override
    public void processEvent(Event event) 
    {
         	
        OMMItemEvent ie = (OMMItemEvent) event;
        OMMMsg respMsg = ie.getMsg();
        assert respMsg.getMsgModelType() == RDMMsgTypes.LOGIN;

        if (respMsg.isFinal()) 
        {
            processLoginFailure(respMsg);
        }
        else if (respMsg.getState().getStreamState() == OMMState.Stream.OPEN
                && respMsg.getState().getDataState() == OMMState.Data.OK
                && currentState != LoginState.LOGGED_IN) 
        {
            processLoginSuccess(respMsg);
        }
    }

    private void processLoginSuccess(OMMMsg respMsg) 
    {
        currentState = LoginState.LOGGED_IN;
        mainApp.onLoginSuccess();
    }

    private void processLoginFailure(OMMMsg respMsg) 
    {
        currentState = LoginState.DENIED;
        mainApp.onLoginFailure();
    }

 
}